<template>
  <div class="note-layouts">
    <div class="note-content" ref="meetingContentRef">
      <div class="left">
        <div class="add-note">
          <el-popover
            ref="popover"
            placement="bottom"
            :width="260"
            trigger="click"
          >
            <template #reference>
              <el-button
                type="primary"
                style="width: 100%"
                @click="addNoteVisible = true"
              >
                新建
              </el-button>
            </template>
            <div class="add-items">
              <div
                style="
                  display: flex;
                  justify-content: center;
                  align-items: center;
                  flex-direction: column;
                "
                v-for="item in staticNoteList"
                :key="item.id"
              >
                <el-icon
                  @click="handleToggleCom(item.name)"
                  style="cursor: pointer"
                  color="#409eff"
                  :class="[
                    item.id === 1 && 'doc-theme-color',
                    item.id === 2 && 'xmind-theme-color',
                    item.id === 3 && 'flow-chart-color',
                  ]"
                  :size="48"
                >
                  <Component :is="item.icon"></Component>
                </el-icon>
                <div style="font-size: 12px">{{ item.text }}</div>
              </div>
            </div>
          </el-popover>
          <el-button
            @click="handleGetNoteLatestList"
            style="width: 100%; margin: 0"
            :loading="loading"
          >
            最新
          </el-button>
        </div>
        <div class="shortcuts">
          <div class="operations" ref="operationRef">
            <!-- 快捷方式  -->
            <el-tree
              ref="shortCutTreeRef"
              :data="shortCutData"
              :props="defaultProps"
              @node-click="handleClickCut"
              :default-expand-all="isExpandAll"
              :expand-on-click-node="false"
              node-key="id"
              @node-expand="closeOtherPopover"
              @node-collapse="closeOtherPopover"
              @node-contextmenu="handleContextmenu"
              highlight-current
              style="width: 100%"
            >
              <template #default="{ node, data }">
                <div class="custom-tree-node">
                  <div
                    style="
                      width: 100%;
                      display: flex;
                      align-items: center;
                      gap: 2px;
                    "
                  >
                    <el-icon v-if="node.level === 1" color="#4bc451">
                      <Paperclip />
                    </el-icon>
                    <el-icon
                      v-if="data.icon && node.level !== 1"
                      :class="[
                        data.icon === 'Document' && 'doc-theme-color',
                        data.icon === 'Xmind' && 'xmind-theme-color',
                        data.icon === 'FlowChart' && 'flow-chart-color',
                      ]"
                    >
                      <Component :is="MapComponent[data.icon]"></Component>
                    </el-icon>
                    <el-icon v-else-if="data.type === 3">
                      <PriceTag />
                    </el-icon>
                    <el-icon
                      v-else-if="data.type === 1 && !node.expanded"
                      size="16"
                      color="#f8b83f"
                    >
                      <Folder />
                    </el-icon>
                    <el-icon
                      v-else-if="data.type === 1 && node.expanded"
                      size="16"
                      color="#f8b83f"
                    >
                      <FolderOpened />
                    </el-icon>
                    <!-- {{ node.label }} -->
                    <!-- <el-text
                      class="mb-2"
                      style="padding-right: 10px; width: 120px"
                      truncated
                    >
                      {{ node.label }}
                    </el-text> -->
                    <el-text style="padding-right: 10px; width: 80%" truncated>
                      {{ node.label }}
                    </el-text>
                  </div>
                </div>
              </template>
            </el-tree>
            <div v-show="showTreeMenu" class="shortTreeMenu">
              <div
                class="btns-wrapper"
                style="display: flex; flex-direction: column"
              >
                <el-button
                  style="
                    margin: 0 !important;
                    border: none !important;
                    justify-content: flex-start;
                  "
                  @click="handleDeleteShortCut"
                >
                  移除快捷方式
                </el-button>
              </div>
            </div>
            <!-- 笔记本文件夹 -->
            <FolderTree
              v-model="selectedFolder"
              ref="folderRef"
              @hide="handleFolderHide"
              @clearHighLight="clearTagTreeHighLight"
            ></FolderTree>
            <!-- 标签列表 -->
            <TagTree
              v-model="selectedTag"
              ref="tagRef"
              @hide="handleTagHide"
              @clearHighLight="clearFolderTreeHighLight"
            ></TagTree>
            <div
              class="btns"
              style="
                display: flex;
                flex-direction: column;
                margin-top: 20px;
                gap: 10px;
              "
            >
              <el-button @click="handleToShare" style="width: 100%; margin: 0">
                分享
              </el-button>
              <el-button
                @click="handleToNoteChart"
                style="width: 100%; margin: 0"
              >
                笔记图谱
              </el-button>
              <el-badge
                :is-dot="noReadNum > 0"
                class="item"
                style="width: 100%; margin: 0"
              >
                <el-button
                  @click="
                    () => {
                      router.push('/file/note-space')
                    }
                  "
                  style="width: 100%; margin: 0"
                >
                  笔记空间
                </el-button>
              </el-badge>
            </div>
          </div>
          <div
            class="btns"
            style="
              display: flex;
              flex-direction: column;
              margin-top: 10px;
              padding-right: 18px;
            "
          >
            <el-button
              @click="handleToRecycle"
              style="width: 100%"
              type="danger"
            >
              回收站
            </el-button>
          </div>
        </div>
      </div>
      <div class="resize">⋮</div>
      <div class="right">
        <router-view></router-view>
      </div>
    </div>
    <el-popover
      ref="popover"
      placement="left-end"
      :width="800"
      :visible="aiWindowVisible"
    >
      <template #reference>
        <div
          style="position: fixed; right: 20px; bottom: 80px; cursor: pointer"
          @click="
            () => {
              aiWindowVisible = !aiWindowVisible
            }
          "
        >
          <el-icon style="font-size: 48px; color: #4093ff">
            <AiIcon></AiIcon>
          </el-icon>
        </div>
      </template>
      <template #default>
        <div
          class="flex justify-content-between padding-tb-5"
          style="border-bottom: var(--el-border)"
        >
          <div class="flex align-items-center">
            <el-icon
              style="font-size: 28px; color: #4093ff"
              class="font-size-4xl"
            >
              <AiIcon></AiIcon>
            </el-icon>
            <span class="font-bold"> 智能问答</span>
          </div>
          <el-icon
            class="pointer font-size-3xl"
            @click="() => (aiWindowVisible = false)"
          >
            <component is="Close" />
          </el-icon>
        </div>
        <div
          style="
            height: 900px;
            max-height: calc(100vh - 80px);
            position: relative;
          "
        >
          <ai-chat />
        </div>
      </template>
    </el-popover>
  </div>
</template>
<script setup>
import { ref, onMounted, provide, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import TagTree from './components/TagTree.vue'
import FolderTree from './components/FolderTree.vue'
import {
  httpCreateNote,
  httpDeleteShortCut,
  httpGetNoReadMsgList,
} from '@/api/note'
import { ElMessage } from 'element-plus'
import useNoteStore from '@/stores/note'
import { storeToRefs } from 'pinia'
import useNote from '@/hooks/useNote'
import { FolderOpened, PriceTag, Paperclip } from '@element-plus/icons-vue'
import AiIcon from '@/icons/Ai.vue'
import AiChat from '@/views/note/components/AiChat.vue'

const { MapJump, MapComponent, staticNoteList } = useNote()
const router = useRouter()
const noteState = useNoteStore()
const {
  selectedFolder,
  selectedTag,
  shortCutData,
  queryNote,
  loading,
  noteData,
  noReadNum,
} = storeToRefs(noteState)
const addNoteVisible = ref(false)
const popover = ref()
const isExpandAll = ref(true)
const folderRef = ref()
const tagRef = ref()
const showTreeMenu = ref(false)
const shortCutTreeRef = ref()
const operationRef = ref()
const aiWindowVisible = ref(false)
provide('operationDom', operationRef)
noteState.getShortCutList()
let pathMap = {
  2: '/file/doc/',
  3: '/file/mindmap/',
  4: '/file/drawio/',
}
const createNoteWithIcon = async (icon, pathIndex) => {
  const res = await httpCreateNote({
    folder_id: 0,
    title: '',
    content: '',
    icon,
    label_id_list: [],
  })
  if (res) {
    await router.push(pathMap[pathIndex] + res.id)
    await noteState.getFolderListData()
  }
}
const handleGetNoteLatestList = () => {
  queryNote.value.sort_order = 1
  selectedFolder.value = noteData.value[0]
  // router.push('/file/note')
  noteState.getList()
  // router.push('/file/note/' + selectedFolder.value.id)
}
const handleToggleCom = (item) => {
  popover.value.hide()
  if (item === 'note') {
    // Document
    createNoteWithIcon('Document', 2)
  } else if (item === 'flow') {
    //FlowChart
    createNoteWithIcon('FlowChart', 4)
  } else if (item === 'xmind') {
    // Xmind
    createNoteWithIcon('Xmind', 3)
  }
  addNoteVisible.value = false
}
// 移除节点高亮
const clearFolderTreeHighLight = () => {
  folderRef.value.setFolderTreeRefKey(null)
  shortCutTreeRef.value.setCurrentKey(null)
}
// 移除节点高亮
const clearTagTreeHighLight = () => {
  tagRef.value.setTagTreeRefKey(null)
  shortCutTreeRef.value.setCurrentKey(null)
}
// 点击文件夹 关闭其他树形 弹窗
const handleFolderHide = () => {
  tagRef.value.close()
}
// 点击标签 关闭其他树形 弹窗
const handleTagHide = () => {
  folderRef.value.closePopOver()
}
// 点击快捷方式
const closeOtherPopover = () => {
  handleFolderHide()
  handleTagHide()
  showTreeMenu.value = false
}
const handleClickCut = (data, node) => {
  tagRef.value.setTagTreeRefKey(null)
  folderRef.value.setFolderTreeRefKey(null)
  closeOtherPopover()
  if (node.level === 1) return
  if (data.type === 1) {
    selectedFolder.value = data
    selectedTag.value = null
    router.push('/file/note')
  } else if (data.type === 3) {
    selectedFolder.value = null
    selectedTag.value = data
    router.push('/file/note')
  } else {
    MapJump[data.icon](data.id)
  }
}
const appendParentData = ref()
// 删除快捷方式
const handleDeleteShortCut = async () => {
  const res = await httpDeleteShortCut({
    shortcut_id: appendParentData.value.id,
    shortcut_type: appendParentData.value.type,
  })
  if (res) {
    await noteState.getShortCutList()
    ElMessage.success('快捷方式移除成功')
    await router.push('/file/note/1')
  }
}

function handleContextmenu(event, data, node) {
  handleFolderHide()
  handleTagHide()
  if (node.level === 1 || !data.top) {
    showTreeMenu.value = false
  } else {
    appendParentData.value = data
    event.preventDefault()
    showTreeMenu.value = true // 显示菜单
    const mouseY = event.clientY // 获取鼠标右击事件的垂直坐标
    const viewportHeight = window.innerHeight // 获取视口的高度
    const distanceToBottom = viewportHeight - mouseY // 计算距离视口底部的距离
    if (distanceToBottom < 150) {
      document
        .querySelector('.shortTreeMenu')
        .setAttribute(
          'style',
          `top:${event.clientY - 100}px;left:${event.clientX + 10}px;`,
        )
    } else {
      document
        .querySelector('.shortTreeMenu')
        .setAttribute(
          'style',
          `top:${event.clientY}px;left:${event.clientX + 10}px;`,
        )
    }
    document.addEventListener('click', closePopOver)
    document.addEventListener('contextmenu', closePopOver)
  }
}

function closePopOver() {
  showTreeMenu.value = false
}

provide('closeShortCut', closePopOver)
watch(
  () => showTreeMenu.value,
  () => {
    if (showTreeMenu.value) {
      nextTick(() => {
        operationRef.value.style.overflow = 'hidden'
      })
    } else {
      nextTick(() => {
        operationRef.value.style.overflow = 'auto'
      })
    }
  },
)
const handleToRecycle = () => {
  router.push('/file/recycle')
}
const handleToShare = () => {
  router.push('/file/share')
}
const handleToNoteChart = () => {
  router.push('/file/graph')
}

const defaultProps = {
  children: 'children',
  label: 'label',
}

function dragControllerDiv() {
  let resize = document.getElementsByClassName('resize')
  let left = document.getElementsByClassName('left')
  let mid = document.getElementsByClassName('right')
  let box = document.getElementsByClassName('note-content')
  for (let i = 0; i < resize.length; i++) {
    // 鼠标按下事件
    resize[i].onmousedown = function (e) {
      //颜色改变提醒
      // resize[i].style.background = '#818181'
      resize[i].style.background = '#ccc'
      let startX = e.clientX
      resize[i].left = resize[i].offsetLeft
      // 鼠标拖动事件
      document.onmousemove = function (e) {
        let endX = e.clientX
        let moveLen = resize[i].left + (endX - startX) // （endx-startx）=移动的距离。resize[i].left+移动的距离=左边区域最后的宽度
        let maxT = box[i].clientWidth - resize[i].offsetWidth // 容器宽度 - 左边区域的宽度 = 右边区域的宽度
        // 左边最大宽度为400px
        if (moveLen > 500) {
          moveLen = 500
        }
        // if (moveLen < 32) {
        //   moveLen = 32
        // } // 左边区域的最小宽度为32px
        if (moveLen > maxT - 150) {
          moveLen = maxT - 150
        } //右边区域最小宽度为150px
        resize[i].style.left = e.clientX // 设置左侧区域的宽度
        for (let j = 0; j < left.length; j++) {
          left[j].style.width = moveLen + 'px'
          mid[j].style.width = box[i].clientWidth - moveLen - 10 + 'px'
        }
      }
      // 鼠标松开事件
      document.onmouseup = function () {
        //颜色恢复
        resize[i].style.background = '#d6d6d6'
        document.onmousemove = null
        document.onmouseup = null
        resize[i].releaseCapture && resize[i].releaseCapture() //当你不在需要继续获得鼠标消息就要应该调用ReleaseCapture()释放掉
      }
      resize[i].setCapture && resize[i].setCapture() //该函数在属于当前线程的指定窗口里设置鼠标捕获
      return false
    }
  }
}
const getNoreadMsg = async () => {
  const res = await httpGetNoReadMsgList()
  if (res) {
    noteState.setNoReadNum(res.num)
  }
}
getNoreadMsg()
onMounted(() => {
  dragControllerDiv()
})
</script>
<style scoped lang="scss">
.shortTreeMenu {
  font-size: 14px;
  position: fixed;
  // padding: 2px 0px 5px;
  z-index: 99999; // 为了显示再最上层
  top: 50%;
  left: 50%;
  background-color: #fff;
  overflow: hidden; // 溢出的部分隐藏
  border-radius: 5px; // 圆角
  border: 1px solid #e6ebf5;

  div:hover {
    cursor: pointer;
  }
}

.note-wrapper {
  height: 100%;
}

.note-layouts {
  // height: calc(100vh - 100px);
  height: calc(100vh - 60px);
}

.note-content {
  display: flex;
  height: 100%;

  .line {
    width: 2px;
    background-color: #000;
    height: 100%;
  }

  .left {
    width: 210px;
    overflow-x: hidden;
    height: calc(100vh - 30px);

    .add-note {
      display: flex;
      flex-direction: column;
      padding: 4px 0;
      gap: 4px;
      height: 102px;
    }

    .shortcuts {
      // width: fit-content;
      height: calc(100% - 102px);
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .operations {
        height: 100%;
        width: 100%;
        overflow-y: auto;
        overflow-x: hidden;
        padding-right: 10px;
        @include scrollBar;
      }
    }
  }

  .right {
    // width: 80%;
    // height: 100%;
    height: calc(100vh - 30px);
    flex: 1;
    overflow: hidden;
    // height: 100%;
  }
}

.resize {
  cursor: col-resize;
  float: left;
  position: relative;
  top: 45%;
  background-color: #ccc;
  border-radius: 5px;
  margin-top: -10px;
  width: 10px;
  height: 50px;
  background-size: cover;
  background-position: center;
  font-size: 32px;
  color: white;
}

.resize:hover {
  color: #444444;
}

.custom-tree-node {
  width: 100%;
  display: flex;
  gap: 14px;
  align-items: center;
  justify-content: space-between;
}

.add-items {
  display: flex;
  padding: 10px 0;
  gap: 20px;
  align-items: center;
  justify-content: center;
}
</style>
